package org.lqq.serverRegisterAndFinder.serverFinder.eureka;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import org.lqq.entity.DefaultServerAddress;
import org.lqq.entity.ServerAddress;
import org.lqq.serverRegisterAndFinder.serverFinder.AbstractServerFinder;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Created by 李清泉 on 2017/10/26.
 *
 * @remark
 */
public class ServerFinder extends AbstractServerFinder {
    private EurekaClient discoveryClient;

    public ServerFinder(EurekaClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    @Override
    public Collection<ServerAddress> discoverServerAddress(String serverName) {
        List<InstanceInfo> infos = discoveryClient.getInstancesByVipAddressAndAppName(null,serverName,false);

        List<ServerAddress> list = new ArrayList<>();
        for (int i = 0; i < infos.size(); i++) {
            InstanceInfo instanceInfo = infos.get(i);
            DefaultServerAddress serverAddress = new DefaultServerAddress();
            serverAddress.setHost(instanceInfo.getHostName());
            serverAddress.setName(instanceInfo.getAppName());
            serverAddress.setPort(instanceInfo.getPort());
            list.add(serverAddress);
        }
        return list;
    }


    @Override
    public Collection<String> discoverAllRegisterdServerName() {
        Applications applications = discoveryClient.getApplications();
        if (applications == null) {
            return Collections.emptyList();
        } else {
            List<Application> registered = applications.getRegisteredApplications();
            List<String> names = new ArrayList();
            Iterator var4 = registered.iterator();

            while (var4.hasNext()) {
                Application app = (Application) var4.next();
                if (!app.getInstances().isEmpty()) {
                    names.add(app.getName().toLowerCase());
                }
            }
            return names;
        }
    }


}

